<?php
namespace Cola\Ext\Log;

/**
 *
 */

class File extends Base
{
    public $config = array(
        'mode' => 0777,
        'dir' => '/tmp/',
    );

    protected static $record = [];

    protected $channel = 'default';

    public function __construct(array $config = array())
    {
        parent::__construct($config);

        $this->config['dir'] = rtrim($this->config['dir'], '/') . '/';
    }

    public function write($text)
    {
        static::$record[$this->channel][] = $text;
    }

    /**
     *
     * 由于mkdir的mode参数会受系统的umask值影响而导致不能赋予777权限，所以这里手动再调用一次chmod来改变目录权限
     *
     * @param string   $path
     * @param int      $mode
     * @param bool     $recursive
     *
     * @return bool
     */
    protected function mkchdir($path, $mode, $recursive = false)
    {
        $ret = mkdir($path, $mode, $recursive);
        $ret &= chmod($path, $mode);

        return boolval($ret);
    }

    public function shutdown()
    {
        $dir = $this->config['dir'];
        is_dir($dir) || $this->mkchdir($dir, $this->config['mode'], true);

        foreach (static::$record as $channel => $content) {
            $text = implode(PHP_EOL, $content);

            file_put_contents($this->config['dir'] . date('d') . '_' . $channel . '_' . PHP_SAPI . '.log', "{$text}" . PHP_EOL, FILE_APPEND | LOCK_EX);
        }


    }


}

